package com.senthink.gl.business.common.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.List;

/**
 * @author yuanpeng@senthink.com
 * @data 2018-01-29 9:59
 */
public final class JacksonUtil {

    public static ObjectMapper objectMapper;

    /**
     * 把JavaBean转换为json字符串
     *
     * @param object
     * @return
     */
    public static String toJSon(Object object) {
        if (objectMapper == null) {
            objectMapper = new ObjectMapper();
        }
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T toBean(String json,Class<T> c){
        Gson gson = new Gson();
        return gson.fromJson(json,c);
    }

    public static <T> List<T> toList(String json){
        Gson gson = new Gson();
        return gson.fromJson(json, new TypeToken<List<T>>(){}.getType());
    }
}
